﻿Imports OpenDelib.ServiceDeliberations

Public MustInherit Class ListeDossiersPage(Of TDossier As DossierDeliberation)
    Inherits OpenDelibPage

    Public Class ResultatListeDossiersDeliberation
        Inherits OperationResult
        Public Property Dossiers As List(Of TDossier)

        Private Sub New()
            MyBase.New()
            Me.Dossiers = New List(Of TDossier)
        End Sub
        Private Sub New(resultat As OperationResult)
            Me.New()
            Me.Connected = resultat.Connected
            Me.ErrorCode = resultat.ErrorCode
            Me.ErrorMessage = resultat.ErrorMessage
            Me.OK = resultat.OK
        End Sub
        Public Sub New(resultat As ResultatListeDossiersDeliberationOfAssembleewn7zOZhO)
            Me.New(CType(resultat, OperationResult))
            For Each dossier As DossierDeliberation In resultat.Dossiers
                Me.Dossiers.Add(CType(dossier, TDossier))
            Next
        End Sub
        Public Sub New(resultat As ResultatListeDossiersDeliberationOfCommissionwn7zOZhO)
            Me.New(CType(resultat, OperationResult))
            For Each dossier As DossierDeliberation In resultat.Dossiers
                Me.Dossiers.Add(CType(dossier, TDossier))
            Next
        End Sub
        Public Sub New(resultat As ResultatListeDossiersDeliberationOfRapportwn7zOZhO)
            Me.New(CType(resultat, OperationResult))
            For Each dossier As DossierDeliberation In resultat.Dossiers
                Me.Dossiers.Add(CType(dossier, TDossier))
            Next
        End Sub
    End Class
    Public Class GridViewBoundField
        Public ReadOnly Property Field As String
        Public ReadOnly Property Text As String
        Public ReadOnly Property Format As String
        Public ReadOnly Property HeaderAlign As HorizontalAlign
        Public ReadOnly Property ItemAlign As HorizontalAlign

        Public Sub New(field As String, text As String, Optional format As String = "", Optional headerAlign As HorizontalAlign = HorizontalAlign.Center, Optional itemAlign As HorizontalAlign = HorizontalAlign.Left)
            Me.Field = field
            Me.Text = text
            Me.Format = format
            Me.HeaderAlign = headerAlign
            Me.ItemAlign = itemAlign
        End Sub
    End Class

    Protected ReadOnly Property TypeDossier As String
        Get
            Return Tools.GetInstance().Parametre(TypeParametre.TypeDossier, Me.TypeDelib)
        End Get
    End Property
    Public ReadOnly Property ListeEtats As ServiceParametre.OIItemListResult
        Get
            Return CType(ViewState("liste_etats"), ServiceParametre.OIItemListResult)
        End Get
    End Property
    Public ReadOnly Property ListeAssistants As ServiceAssistant.OIItemListResult
        Get
            Return CType(ViewState("liste_assistants"), ServiceAssistant.OIItemListResult)
        End Get
    End Property
    Public ReadOnly Property ListesDossiers As Dictionary(Of String, ResultatListeDossiersDeliberation)
        Get
            If Session("listes_dossiers_" & Me.TypeDossier & "_" & Tools.GetInstance.getToken) Is Nothing Then Session("listes_dossiers_" & Me.TypeDossier & "_" & Tools.GetInstance.getToken) = New Dictionary(Of String, ResultatListeDossiersDeliberation)
            Return CType(Session("listes_dossiers_" & Me.TypeDossier & "_" & Tools.GetInstance.getToken), Global.System.Collections.Generic.Dictionary(Of String, ResultatListeDossiersDeliberation))
        End Get
    End Property
    Public MustOverride ReadOnly Property Titre As String
    Protected MustOverride ReadOnly Property TypeDelib As TypeDeliberation
    Protected MustOverride ReadOnly Property LibelleDossier As String
    Protected MustOverride ReadOnly Property LibelleFeminin As Boolean
    Protected MustOverride ReadOnly Property UrlFicheDossier As String
    Protected MustOverride ReadOnly Property HiddenFieldIndexTabs As HiddenField
    Protected MustOverride ReadOnly Property BoutonActualiser As Button
    Protected MustOverride ReadOnly Property BoutonAjouterDossier As Button
    Protected MustOverride ReadOnly Property DivTabs As HtmlGenericControl
    Protected MustOverride ReadOnly Property GridViewsFields As List(Of GridViewBoundField)


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Master.Titre = Me.Titre

        RemoveHandler Me.BoutonActualiser.Click, AddressOf btnActualiser_Click
        AddHandler Me.BoutonActualiser.Click, AddressOf btnActualiser_Click
        RemoveHandler Me.BoutonAjouterDossier.Click, AddressOf btnAjouterDossier_Click
        AddHandler Me.BoutonAjouterDossier.Click, AddressOf btnAjouterDossier_Click

        If Not IsPostBack Then
            ' Chargement de la liste des états de dossier associés au type de dossier
            Using svc As New ServiceParametre.ParametresClient
                Dim params As New ServiceParametre.ListeParametreParameters
                params.Authentication = New ServiceParametre.AuthenticationParameters
                params.Authentication.Token = Tools.GetInstance.getToken
                params.EntiteParametrage = 25
                params.Param1 = Me.TypeDossier
                params.OrdreTri = ServiceParametre.OrdreTri.ParCode

                Try
                    ViewState("liste_etats") = svc.ListeParametre(params)
                Catch ex As Exception
                    ViewState("liste_etats") = Nothing
                    NotifyErreur(ex.Message)
                End Try
            End Using

            ' Chargement de la liste des assistants associés au type de dossier
            Using svc As New ServiceAssistant.AssistantsClient
                Dim params As New ServiceAssistant.ListeDeclencheursAssistantParameters
                params.Authentication = New ServiceAssistant.AuthenticationParameters
                params.Authentication.Token = Tools.GetInstance.getToken
                params.TypeAssistant = 6
                params.TypeDeclencheur = 4
                params.TypeEvenement = 99
                params.CodeParametre = Me.TypeDossier
                params.CodeParametre2 = ""

                Try
                    ViewState("liste_assistants") = svc.ListeAssistantsSelonParametreEtDeclencheur(params)
                Catch ex As Exception
                    ViewState("liste_assistants") = Nothing
                    NotifyErreur(ex.Message)
                End Try
            End Using
        End If

        ' Chargement des onglets
        InitializeTabs()

        If Not IsPostBack Then
            Me.HiddenFieldIndexTabs.Value = "0"
            ' Chargement des listes de dossiers selon leur état
            Search()
        End If

        ' Chargement des listes
        InitializeGridViews()
    End Sub

    Private Sub btnActualiser_Click(sender As Object, e As EventArgs)
        Search()
        InitializeGridViews()
    End Sub

    Private Sub btnAjouterDossier_Click(sender As Object, e As EventArgs)
        Response.Redirect(Me.UrlFicheDossier & "?modeFiche=0")
    End Sub

    Private Sub gvDossier_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs)
        Dim codeDossier As String = ""

        Dim row As GridViewRow = CType(CType(e.CommandSource, Control).NamingContainer, GridViewRow)
        codeDossier = CType(row.Cells(row.Cells.Count - 1).Controls(0), Label).Text

        Select Case e.CommandName.ToUpper
            Case "MODIFIER"
                Response.Redirect(Me.UrlFicheDossier & "?modeFiche=1&cle=" & codeDossier)

            Case "SUPPRIMER"
                Using svc As New ServiceDossiers.DossiersClient
                    Dim params As New ServiceDossiers.ParametresSuppressionDossier
                    params.Authentication = New ServiceDossiers.AuthenticationParameters
                    params.Authentication.Token = Tools.GetInstance.getToken
                    params.Code = codeDossier
                    params.SuppressionTotale = True

                    Try
                        Dim results As ServiceDossiers.OperationResult
                        results = svc.Suppression(params)
                        If results.OK Then
                            NotifySuccess("Suppression effectuée avec succès.")
                            Search()
                            InitializeGridViews()
                        Else
                            NotifyErreur(results.ErrorMessage)
                        End If
                    Catch ex As Exception
                        NotifyErreur(ex.Message)
                    End Try
                End Using

            Case "ASSISTANT"
                Dim codeAss As String = CStr(e.CommandArgument)
                Using svc As New ServiceAssistant.AssistantsClient
                    Dim params As New ServiceAssistant.AssistantParameters
                    params.Authentication = New ServiceAssistant.AuthenticationParameters
                    params.Authentication.Token = Tools.GetInstance.getToken
                    params.CleEntite = codeDossier
                    params.CodeAssistant = codeAss

                    Try
                        Dim results As ServiceAssistant.OperationResult
                        results = svc.LancerAssistant(params)
                        If results.OK Then
                            NotifySuccess("Opération effectuée avec succès.")
                            Search()
                            InitializeGridViews()
                        Else
                            NotifyErreur(results.ErrorMessage)
                        End If
                    Catch ex As Exception
                        NotifyErreur(ex.Message)
                    End Try
                End Using

        End Select
    End Sub


    Private Sub InitializeTabs()
        ' Cette fonction permet de créer un onglet par état de dossier associé au type de dossier

        ' Mise à blanc des onglets
        Me.DivTabs.Controls.Clear()

        ' Prise en charge des erreurs de lecture des états de dossiers, ou si aucun état de dossier n'a été associé au type de dossier
        If ListeEtats Is Nothing OrElse Not ListeEtats.OK Then
            Me.DivTabs.InnerText = "Impossible de charger les états de dossier associés au type de dossier '" & Me.TypeDossier & "'" & If(ListeEtats IsNot Nothing, " :" & ControlChars.NewLine & ListeEtats.ErrorMessage, ".")
            Return
        ElseIf ListeEtats.Liste.Count <= 0 Then
            Me.DivTabs.InnerText = "Aucun état de dossier n'est associé au type de dossier '" & Me.TypeDossier & "'."
            Return
        Else
            Dim ul As New HtmlGenericControl("ul")
            Me.DivTabs.Controls.Add(ul)
        End If

        ' Ajout des onglets
        For Each item As ServiceParametre.OIItem In ListeEtats.Liste
            AddTab(item.Code, item.Libelle)
        Next
    End Sub
    Private Sub AddTab(code As String, text As String)
        Dim div As HtmlControls.HtmlControl
        Dim li As HtmlControls.HtmlControl
        Dim a As HtmlControls.HtmlAnchor
        Dim gv As GridView
        Dim id As String

        id = "tb" & code

        ' Ajout du contenu de l'onglet
        div = New HtmlGenericControl("div")
        div.ID = id

        ' Création du datagrid
        gv = New Odyssee.WebControles.AcroGridView()
        gv.AllowPaging = False
        gv.AllowSorting = False
        gv.AutoGenerateColumns = False
        gv.AutoGenerateDeleteButton = False
        gv.AutoGenerateEditButton = False
        gv.AutoGenerateSelectButton = False
        gv.ClientIDMode = UI.ClientIDMode.Static
        gv.CssClass = "grid"
        gv.DataSource = Nothing
        gv.EmptyDataRowStyle.HorizontalAlign = HorizontalAlign.Center
        gv.EmptyDataText = "Aucun" & If(Me.LibelleFeminin, "e", "") & " " & Me.LibelleDossier
        gv.ID = "gv" & code
        gv.ShowHeaderWhenEmpty = True

        For Each field As GridViewBoundField In Me.GridViewsFields
            gv.Columns.Add(InitializeBoundField(field))
        Next
        gv.Columns.Add(InitializeButtonsColumn())

        AddHandler gv.RowCommand, AddressOf gvDossier_RowCommand

        div.Controls.Add(gv)
        Me.DivTabs.Controls.Add(div)

        ' Ajout de l'en-tête de l'onglet
        li = New HtmlControls.HtmlGenericControl("li")
        a = New HtmlControls.HtmlAnchor()
        a.HRef = "#" & div.ClientID
        a.InnerText = text 'HttpUtility.HtmlEncode(text)
        li.Controls.Add(a)
        Me.DivTabs.Controls(0).Controls.Add(li)
    End Sub
    Private Shared Function InitializeBoundField(field As GridViewBoundField) As Odyssee.WebControles.BoundField
        Dim col As Odyssee.WebControles.BoundField
        col = New Odyssee.WebControles.BoundField()
        col.DataFormatString = field.Format
        col.DataField = field.Field
        col.HeaderStyle.HorizontalAlign = field.HeaderAlign
        col.HeaderText = field.Text
        col.HtmlEncode = True
        col.ItemStyle.HorizontalAlign = field.ItemAlign
        col.ReadOnly = True
        col.SortExpression = field.Field
        Return col
    End Function
    Private Function InitializeButtonsColumn() As TemplateField
        Dim col As TemplateField

        ' Prise en charge des erreurs de lecture des assistants
        If ListeAssistants Is Nothing OrElse Not ListeAssistants.OK Then
            Me.DivTabs.InnerText = "Impossible de charger les assistants associés au type de dossier '" & Me.TypeDossier & "'" & If(ListeAssistants IsNot Nothing, " :" & ControlChars.NewLine & ListeAssistants.ErrorMessage, ".")
        End If

        col = New TemplateField()
        col.HeaderStyle.HorizontalAlign = HorizontalAlign.Right
        col.HeaderTemplate = New ButtonsGridViewTemplate(DataControlRowType.Header, ListeAssistants, Me.LibelleDossier, Me.LibelleFeminin)
        col.ItemStyle.HorizontalAlign = HorizontalAlign.Right
        col.ItemTemplate = New ButtonsGridViewTemplate(DataControlRowType.DataRow, ListeAssistants, Me.LibelleDossier, Me.LibelleFeminin)
        col.SortExpression = ""
        Return col
    End Function

    Private Sub Search()
        Me.ListesDossiers.Clear()

        If ListeEtats Is Nothing OrElse
           Not ListeEtats.OK OrElse
           ListeEtats.Liste.Count <= 0 Then Return

        ' Initialisation du service
        Using svc As New DeliberationsClient

            ' Initialisation des paramètres de recherche
            Dim params As New ParametresListe
            params.Authentication = New AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken

            ' Pour chaque état de dossier
            For Each item As ServiceParametre.OIItem In ListeEtats.Liste
                params.Etat = item.Code

                Try
                    ' Recherche des dossiers et chargement du gridview associé
                    Me.ListesDossiers.Add(item.Code, Search(svc, params))
                Catch ex As Exception
                    Me.ListesDossiers.Add(item.Code, Nothing)
                    NotifyErreur(ex.Message)
                End Try
            Next
        End Using
    End Sub
    Protected MustOverride Function Search(svc As DeliberationsClient, params As ParametresListe) As ResultatListeDossiersDeliberation

    Private Sub InitializeGridViews()
        If ListeEtats Is Nothing OrElse
           Not ListeEtats.OK OrElse
           ListeEtats.Liste.Count <= 0 Then Return

        ' Pour chaque état de dossier
        For Each item As ServiceParametre.OIItem In ListeEtats.Liste

            ' Prise en charge des erreurs de lecture des dossiers
            If ListesDossiers(item.Code) Is Nothing OrElse Not ListesDossiers(item.Code).OK Then
                NotifyErreur("Impossible de charger les dossiers de type '" & Me.TypeDossier & "' à l'état '" & item.Code & "'" & If(ListesDossiers(item.Code) IsNot Nothing, " :" & ControlChars.NewLine & ListesDossiers(item.Code).ErrorMessage, "."))
                Continue For
            End If

            ' Recherche du gridview associé
            Dim gv As GridView = CType(Odyssee.WebControles.Tools.FindControlOnPage(Me, "gv" & item.Code, False), GridView)
            If gv Is Nothing Then
                NotifyErreur("Impossible de trouver la liste associée à l'état de dossier '" & item.Libelle & "' (code : '" & item.Code & "').")
                Continue For
            End If

            gv.DataSource = ListesDossiers(item.Code).Dossiers
            gv.DataBind()
        Next
    End Sub

    Private Function GetPropertyValue(obj As Object, propName As String) As Object
        Dim objType As Type = obj.GetType()
        Dim pInfo As System.Reflection.PropertyInfo = objType.GetProperty(propName)
        Dim propValue As Object = pInfo.GetValue(obj, Reflection.BindingFlags.GetProperty, Nothing, Nothing, Nothing)
        Return PropValue
    End Function

End Class
